<link rel="stylesheet" href="../../js/lay-module/step-lay/step.css" media="all">
<div class="layuimini-main">
	<div class="layui-carousel" id="stepForm" lay-filter="stepForm" style="margin: 0 auto;">
		<div carousel-item>
			<div id="firstForm">
				<div class="layui-form layuimini-form" lay-filter="baseFormItem">
					<div class="layui-form-item">
						<label class="layui-form-label required">应用名称</label>
						<div class="layui-input-block">
							<input type="text" name="appName" lay-verify="required" lay-reqtext="应用名称不能为空" placeholder="请输入应用名称" autocomplete="off" class="layui-input" disabled="">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label required">技术类型</label>
						<div class="layui-input-block">
							<select name="techType" disabled="">
								<option value="">请选择</option>
								<option value="1">SpringBoot</option>
								<option value="2">Vue</option>
								<option value="3">React</option>
							</select>
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label required">代码仓库地址</label>
						<div class="layui-input-block">
							<input name="codeRepoPath" lay-verify="required" lay-reqtext="代码仓库地址不能为空" placeholder="如：GitLab的项目ID" autocomplete="off"  class="layui-input">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label">亲密应用</label>
						<div class="layui-input-inline" style="width: 39%">
							<div id="affinityAppName"></div>
						</div>
						<div class="layui-form-mid layui-word-aux">会尽量与亲密应用部署在相同节点上</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label">一级部门</label>
						<div class="layui-input-block">
							<input type="text" name="firstDepartment" placeholder="请输入一级部门" autocomplete="off" class="layui-input">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label">二级部门</label>
						<div class="layui-input-block">
							<input type="text" name="secondDepartment" placeholder="请输入二级部门" autocomplete="off" class="layui-input">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label">三级部门</label>
						<div class="layui-input-block">
							<input type="text" name="thirdDepartment" placeholder="请输入三级部门" autocomplete="off" class="layui-input">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label">描述</label>
						<div class="layui-input-block">
							<input type="text" name="description" placeholder="至多100字" autocomplete="off" class="layui-input">
						</div>
					</div>
					<input type="hidden" id="appId" name="appId">
					<div class="layui-form-item">
						<div class="layui-input-block">
							<button class="layui-btn layui-btn-normal" lay-submit id="saveBtn" lay-filter="saveBtn">确认保存</button>
						</div>
					</div>
				</div>
			</div>
			<div id="secondForm">
				<div class="layui-form layuimini-form" id="springBootFormItem" lay-filter="springBootFormItem">
					<div class="layui-form-item">
						<label class="layui-form-label required">构建方式</label>
						<div class="layui-input-block">
							<select name="extendSpringBootParam.packageBuildType">
								<option value="">请选择</option>
								<option value="1">Maven</option>
								<!--
								<option value="2">Gradle</option>
								-->
							</select>
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label">文件路径</label>
						<div class="layui-input-block">
							<input name="extendSpringBootParam.packageTargetPath" placeholder="以应用作为根目录，默认路径：target/" autocomplete="off"  class="layui-input">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label required">文件类型</label>
						<div class="layui-input-block">
							<select name="extendSpringBootParam.packageFileType" lay-filter="extendSpringBootParam.packageFileType" lay-verify="required" lay-reqtext="文件类型不能为空" id="packageFileType2">
								<option value="">请选择</option>
								<option value="1">Jar</option>
								<option value="2">War</option>
								<!--
								<option value="3">Zip</option>
								-->
							</select>
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label required">基础镜像来源</label>
						<div class="layui-input-block">
							<select name="baseImageSource" lay-filter="baseImageSource" id="baseImageSource2" lay-verify="required" lay-reqtext="基础镜像来源不能为空">
								<option value="">请选择</option>
								<option value="1">版本号</option>
								<option value="2">自定义</option>
							</select>
						</div>
					</div>
					<div class="layui-form-item" style="display:none" id="baseImageVersionDiv2">
						<label class="layui-form-label required" id="baseImageLabel">Tomcat版本</label>
						<div class="layui-input-inline">
							<select name="baseImageVersion" lay-filter="baseImageVersion" id="baseImageVersion2">
								<option value="">请选择</option>
								<option value="10">v10</option>
								<option value="9">v9</option>
								<option value="8">v8</option>
							</select>
						</div>
						<div class="layui-form-mid layui-word-aux" id="baseImageVersionDesc">会自动下载依赖包，请确保能够访问外网</div>
					</div>
					<div class="layui-form-item" style="display:none" id="baseImageDiv2">
						<label class="layui-form-label required">基础镜像</label>
						<div class="layui-input-inline" style="width: 350px;">
							<input type="text" name="baseImage" id="baseImage2" placeholder="如：openjdk:11.0.16-jdk" autocomplete="off" class="layui-input">
						</div>
						<div class="layui-form-mid layui-word-aux" id="baseImageDesc"><a href="#" target="_blank">《镜像制作指引》</a></div>
					</div>
					<div class="layui-form-item required">
						<div class="layui-input-block">
							<button type="button" class="layui-btn layui-btn-primary pre">上一步</button>
							<button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
						</div>
					</div>
				</div>
				<div class="layui-form layuimini-form" id="nodeFormItem" lay-filter="nodeFormItem">
					<div class="layui-form-item">
						<label class="layui-form-label required">Node版本</label>
						<div class="layui-input-block">
							<input name="extendNodeParam.nodeVersion" placeholder="如：v16.15.1" autocomplete="off"  class="layui-input">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label required">Npm版本</label>
						<div class="layui-input-block">
							<input name="extendNodeParam.npmVersion" placeholder="如：v8.11.0" autocomplete="off"  class="layui-input">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label">文件路径</label>
						<div class="layui-input-block">
							<input name="extendNodeParam.packageTargetPath" id="extendNodeParam-packageTargetPath" placeholder="以应用作为根目录，默认路径：dist/" autocomplete="off"  class="layui-input">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label required">基础镜像来源</label>
						<div class="layui-input-block">
							<select name="baseImageSourceNode" lay-filter="baseImageSourceNode" id="baseImageSourceNode" lay-verify="required" lay-reqtext="基础镜像来源不能为空">
								<option value="">请选择</option>
								<option value="1">版本号</option>
								<option value="2">自定义</option>
							</select>
						</div>
					</div>
					<div class="layui-form-item" style="display:none" id="baseImageVersionNodeDiv">
						<label class="layui-form-label required" id="baseImageLabel">Nginx版本</label>
						<div class="layui-input-inline">
							<select name="baseImageVersionNode" lay-filter="baseImageVersionNode" id="baseImageVersionNode">
								<option value="">请选择</option>
								<option value="1.23">v1.23</option>
								<option value="1.22">v1.22</option>
								<option value="1.21">v1.21</option>
								<option value="1.20">v1.20</option>
								<option value="1.19">v1.19</option>
								<option value="1.18">v1.18</option>
							</select>
						</div>
						<div class="layui-form-mid layui-word-aux">会自动下载依赖包，请确保能够访问外网</div>
					</div>
					<div class="layui-form-item" style="display:none" id="baseImageNodeDiv">
						<label class="layui-form-label required">基础镜像</label>
						<div class="layui-input-inline" style="width: 350px;">
							<input type="text" name="baseImageNode" id="baseImageNode" placeholder="如：nginx:1.23.3" autocomplete="off" class="layui-input">
						</div>
						<div class="layui-form-mid layui-word-aux"><a href="#" target="_blank">《镜像制作指引》</a></div>
					</div>
					<div class="layui-form-item required">
						<div class="layui-input-block">
							<button type="button" class="layui-btn layui-btn-primary pre">上一步</button>
							<button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtnNode">确认保存</button>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
<script src="../../../js/xm-select.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'step'], function () {
        var form = layui.form,
            layer = layui.layer,
            $ = layui.$,
			step = layui.step,
			parentIndex = layer.index;
		var appId = localStorage.getItem('appId_' + $("#userName").val());
		
		//首先初始化分步表单
		step.render({
            elem: '#stepForm',
            filter: 'stepForm',
            width: '100%',
            stepWidth: '750px',
            height: '500px',
            stepItems: []
        });
		
		var affinityAppName;
		//初始化表单数据
		var loadIndex = 0;
		$.ajax({
			url: '/app/query',
			type: 'POST',
			dataType: "json",
			contentType: 'application/json;charset=UTF-8',
			data: JSON.stringify({'appId': appId}),
			beforeSend: function() {
				loadIndex = layer.load(2);
			},
			success: function(res){
				layer.close(loadIndex);
				if(res.code != "000000"){
					layer.msg(res.message, {icon: 5, shift: 6});
					return false;
				}
				
				$("#appId").val(res.data.id);
				
				//给表单赋值
				form.val("baseFormItem", {
					"appName": res.data.appName
					,"techType": res.data.techType
					,"codeRepoPath": res.data.codeRepoPath
					,"affinityAppNames": res.data.affinityAppNames
					,"firstDepartment": res.data.firstDepartment
					,"secondDepartment": res.data.secondDepartment
					,"thirdDepartment": res.data.thirdDepartment
					,"description": res.data.description
				});
				
				affinityAppName = initApp($, appId, res.data.affinityAppNames);
				
				//Java
				if(res.data.techType == 1){
					$("#saveBtn").attr("lay-filter", "formStep").text("下一步");
					//初始化下个表单
					form.val("springBootFormItem", {
						"extendSpringBootParam.packageBuildType": res.data.appExtend.packageBuildType
						,"extendSpringBootParam.packageFileType": res.data.appExtend.packageFileType
						,"extendSpringBootParam.packageTargetPath": res.data.appExtend.packageTargetPath
						,"baseImageSource": res.data.baseImageSource
					});
					//初始化镜像
					initBaseImage(res.data.appExtend.packageFileType, res.data.baseImageSource,
						res.data.baseImageVersion, res.data.baseImage, $, form);
					$("#springBootFormItem").show();
					$("#nodeFormItem").hide();
				//Vue和React
				}else if(res.data.techType == 2 || res.data.techType == 3){
					$("#saveBtn").attr("lay-filter", "formStep").text("下一步");
					form.val("nodeFormItem", {
						"extendNodeParam.nodeVersion": res.data.appExtend.nodeVersion
						,"extendNodeParam.npmVersion": res.data.appExtend.npmVersion
						,"extendNodeParam.packageTargetPath": res.data.appExtend.packageTargetPath
						,"baseImageSourceNode": res.data.baseImageSource
						,"baseImageVersionNode": res.data.baseImageVersion
						,"baseImageNode": res.data.baseImage
					});
					$("#springBootFormItem").hide();
					$("#nodeFormItem").show();
					
					//版本号
					if(res.data.baseImageSource == 1){
						$("#baseImageVersionNodeDiv").show();
						$("#baseImageNodeDiv").hide();
					//自定义
					}else if(res.data.baseImageSource == 2){
						$("#baseImageVersionNodeDiv").hide();
						$("#baseImageNodeDiv").show();
					}
					if(res.data.techType == 3){
						$("#extendNodeParam-packageTargetPath").attr("placeholder", "以应用作为根目录，默认路径：build/");
					}
				}else{
					$("#saveBtn").attr("lay-filter", "saveBtn").text("确认保存");
				}
			},
			error: function(res){
				layer.close(loadIndex);
				layer.msg(res.message, {icon: 5, shift: 6});				
			}
		});
		
		form.on('select(extendSpringBootParam.packageFileType)', function(data) {
			initBaseImage(data.value, '', '', '', $, form);
        });
		
		form.on('select(baseImageSource)', function(data) {
			var packageFileType = $('#packageFileType2').val();
			initBaseImage(packageFileType, data.value, '', '', $, form);
		});
		
		//Node的镜像来源
		form.on('select(baseImageSourceNode)', function(data) {
			//版本号
			if(data.value == 1){
				$("#baseImageVersionNodeDiv").show();
				$("#baseImageNodeDiv").hide();
			//自定义
			}else if(data.value == 2){
				$("#baseImageVersionNodeDiv").hide();
				$("#baseImageNodeDiv").show();
			}
		});
		
		form.on('submit(formStep)', function (data) {
			var firstFormData = '<div id="firstFormData">';
			firstFormData += '<input type="hidden" name="affinityAppNames" value="'+ affinityAppName.getValue('value') +'"/>';
			var fields = data.field;
			for(var fieldName in fields){
				firstFormData += '<input type="hidden" name="'+ fieldName +'" value="'+ fields[fieldName] +'"/>';
			}
			firstFormData += "</div>";
			//springBoot
			if(data.field.techType == 1){
				$("#springBootFormItem").append(firstFormData);
			//Vue和React
			}else if(data.field.techType == 2 || data.field.techType == 3){
				$("#nodeFormItem").append(firstFormData);
			}
            step.next('#stepForm');
            return false;
        });

        $('.pre').click(function () {
			$("#firstFormData").remove();
            step.pre('#stepForm');
        });
		
        form.on('submit(saveBtn)', function(data) {
			if(data.field.baseImageSource == 1){
				if(data.field.baseImageVersion == ''){
					layer.msg('基础镜像版本不能为空', {icon: 5, shift: 6});
					return false;
				}
				data.field.baseImage = '';
			}else if(data.field.baseImageSource == 2){
				if(data.field.baseImage == ''){
					layer.msg('基础镜像不能为空', {icon: 5, shift: 6});
					return false;
				}
				data.field.baseImageVersion = '';
			}
			if(data.field.affinityAppNames != ''){
				data.field.affinityAppNames = data.field.affinityAppNames.split(',');
			}else{
				data.field.affinityAppNames = [];
			}
			
			var fields = data.field;
			var allParams = {};
			var extendParams = {};
			for(var fieldName in fields){
				var fs = fieldName.split(".");
				if(fs.length > 1){
					extendParams[fs[1]] = fields[fieldName];
				}else{
					allParams[fieldName] = fields[fieldName];
				}
			}
			allParams['extendSpringBootParam'] = extendParams;
		
			$.ajax({
				url: '/app/update',
				type: 'POST',
				dataType: "json",
				contentType: 'application/json;charset=UTF-8',
				data: JSON.stringify(allParams),
				success: function(data){
					if(data.code != "000000"){
						layer.msg(data.message, {icon: 5, shift: 6});
						return false;
					}
					layer.msg("保存成功", {
						icon: 1,
						time: 500,
						shade: 0.01,
						shadeClose: false}, function(){
						layer.close(parentIndex);
						parent.initForm($, appId);
					});
				},
				error: function(data){
					layer.msg(data.message, {icon: 5, shift: 6});
				}
			});
            return false;
        });
		
		//Node
		form.on('submit(saveBtnNode)', function(data) {
		
			data.field.baseImageSource = data.field.baseImageSourceNode;
			data.field.baseImageVersion = data.field.baseImageVersionNode;
			data.field.baseImage = data.field.baseImageNode;
			if(data.field.affinityAppNames != ''){
				data.field.affinityAppNames = data.field.affinityAppNames.split(',');
			}else{
				data.field.affinityAppNames = [];
			}
			
			if(data.field.baseImageSource == 1){
				if(data.field.baseImageVersion == ''){
					layer.msg('基础镜像版本不能为空', {icon: 5, shift: 6});
					return false;
				}
				data.field.baseImage = '';
			}else if(data.field.baseImageSource == 2){
				if(data.field.baseImage == ''){
					layer.msg('基础镜像不能为空', {icon: 5, shift: 6});
					return false;
				}
				data.field.baseImageVersion = '';
			}
			var fields = data.field;
			var allParams = {};
			var extendParams = {};
			for(var fieldName in fields){
				var fs = fieldName.split(".");
				if(fs.length > 1){
					extendParams[fs[1]] = fields[fieldName];
				}else{
					allParams[fieldName] = fields[fieldName];
				}
			}
			allParams['extendNodeParam'] = extendParams;
		
			$.ajax({
				url: '/app/update',
				type: 'POST',
				dataType: "json",
				contentType: 'application/json;charset=UTF-8',
				data: JSON.stringify(allParams),
				success: function(data){
					if(data.code != "000000"){
						layer.msg(data.message, {icon: 5, shift: 6});
						return false;
					}
					layer.msg("保存成功", {
						icon: 1,
						time: 500,
						shade: 0.01,
						shadeClose: false}, function(){
						layer.close(parentIndex);
						parent.initForm($, appId);
					});
				},
				error: function(data){
					layer.msg(data.message, {icon: 5, shift: 6});
				}
			});
            return false;
        });
    });
	
	function initBaseImage(packageFileType, baseImageSource, selectedVersion, baseImageValue, $, form){
		//在非Linux环境下，基础镜像来源不能有“版本号”选项，因为只有制作Linux环境下的Jdk镜像才有意义
		if(packageFileType != ''){
			$.ajax({
				url: '/globalConfig/queryOsName',
				type: 'POST',
				dataType: "json",
				contentType: 'application/json;charset=UTF-8',
				data: JSON.stringify({'1': '1'}),
				success: function(res){
					if(res.code != "000000"){
						return false;
					}
					//在非Linux环境下，基础镜像来源不能有“版本号”选项，因为只有制作Linux环境下的Jdk镜像才有意义
					var opt = '<option value="">请选择</option>';
					if(res.data.indexOf('Linux') >= 0){
						if(baseImageSource == 1){
							opt = opt.concat('<option value="1" selected>版本号</option>');
						}else{
							opt = opt.concat('<option value="1">版本号</option>');
						}
					}
					if(baseImageSource == 2){
						opt = opt.concat('<option value="2" selected>自定义</option>');
					}else{
						opt = opt.concat('<option value="2">自定义</option>');
					}
					
					$("#baseImageSource2").html(opt);
					form.render();
				}
			});
		}else{
			var opt = '<option value="">请选择</option>';
			if(baseImageSource == 1){
				opt = opt.concat('<option value="1" selected>版本号</option>');
			}else{
				opt = opt.concat('<option value="1">版本号</option>');
			}
			if(baseImageSource == 2){
				opt = opt.concat('<option value="2" selected>自定义</option>');
			}else{
				opt = opt.concat('<option value="2">自定义</option>');
			}
			$("#baseImageSource2").html(opt);
			form.render();
		}
	
		//选择了版本号
		if(baseImageSource == 1 && packageFileType != ''){
			initVersion(packageFileType, selectedVersion, $, form);
			$('#baseImageVersionDiv2').show();
			$('#baseImageDiv2').hide();
		//选择了自定义
		}else if(baseImageSource == 2 && packageFileType != ''){
			baseImagePlaceholder(packageFileType, baseImageValue, $, form);
			$('#baseImageVersionDiv2').hide();
			$('#baseImageDiv2').show();
		}else{
			$('#baseImageVersionDiv2').hide();
			$('#baseImageDiv2').hide();
		}
	}
	
	function baseImagePlaceholder(packageFileType, baseImageValue, $, form){
		//Jar
		if(packageFileType == 1){
			$("#baseImage2").val(baseImageValue).attr("placeholder", "如：openjdk:11.0.16-jdk");
			$("#baseImageDesc a").attr("href", "https://github.com/tiandizhiguai/dhorse-doc/blob/main/guide/JDK%E9%95%9C%E5%83%8F%E5%88%B6%E4%BD%9C.md");
		//War
		}else if(packageFileType == 2){
			$("#baseImage2").val(baseImageValue).attr("placeholder", "如：tomcat:9.0.70-jdk11");
			$("#baseImageDesc a").attr("href", "https://github.com/tiandizhiguai/dhorse-doc/blob/main/guide/Tomcat%E9%95%9C%E5%83%8F%E5%88%B6%E4%BD%9C.md");
		}
	}
	
	function initVersion(packageFileType, selectedVersion, $, form){
		//选择了Jar
		if(packageFileType == 1){
			$('#baseImageLabel').text('Java版本');
			$('#baseImageVersionDesc').text('来自Maven配置或DHorse所在的环境');
			initJavaVersion(selectedVersion, $, form);
		 //选择了War
		}else if(packageFileType == 2){
			$('#baseImageLabel').text('Tomcat版本');
			$('#baseImageVersionDesc').text('会自动下载依赖包，请确保能够访问外网');
			initTomcatVersion(selectedVersion, $, form);
		}
	}
	
	function initJavaVersion(selectedVersion, $, form){
		$.ajax({
			url: '/globalConfig/queryJavaVersion',
			type: 'POST',
			dataType: "json",
			contentType: 'application/json;charset=UTF-8',
			data: JSON.stringify({'1': '1'}),
			success: function(res){
				var opt = '<option value="">请选择</option>';
				versions = res.data;
				for(var v in versions){
					if(selectedVersion === versions[v]){
						opt = opt.concat("<option value='"+ versions[v] +"' selected>"+ versions[v] + "</option>");
					}else{
						opt = opt.concat("<option value='"+ versions[v] +"'>"+ versions[v] + "</option>");
					}
				}
				$("#baseImageVersion2").html(opt);
				form.render('select');
			},
			error: function(data){
				layer.msg(data.message, {icon: 5, shift: 6});
			}
		});
	}
	
	function initTomcatVersion(selectedVersion, $, form){
		var opt = '<option value="">请选择</option>';
		if(selectedVersion === "10"){
			opt = opt.concat('<option value="10" selected>v10</option>');
		}else{
			opt = opt.concat('<option value="10">v10</option>');
		}
		if(selectedVersion === "9"){
			opt = opt.concat('<option value="9" selected>v9</option>');
		}else{
			opt = opt.concat('<option value="9">v9</option>');
		}
		if(selectedVersion === "8"){
			opt = opt.concat('<option value="8" selected>v8</option>');
		}else{
			opt = opt.concat('<option value="8">v8</option>');
		}
		$("#baseImageVersion2").html(opt);
		form.render('select');
	}
	
	function initApp($, currentAppId, selectedAffinityAppName){
		var affinityAppName = xmSelect.render({
			el: '#affinityAppName',
			theme: {
				color: '#1cbbb4',
			},
			filterable: true,
			filterMethod: function(val, item, index, prop){
				if(val == item.name){
					return true;
				}
				if(item.name.indexOf(val) != -1){
					return true;
				}
				return false;
			},
			data: [],
	    });
		
		$.ajax({
			url: '/app/search',
			type: 'POST',
			dataType: "json",
			contentType: 'application/json;charset=UTF-8',
			data: JSON.stringify({'1': '1'}),
			success: function(res){
				var orgData = res.data;
				var data = new Array();
				for(var i in orgData){
					//不能选择自己
					if(currentAppId == orgData[i].id){
						continue;
					}
					data.push({'name': orgData[i].appName, 'value': orgData[i].appName});
				}
				affinityAppName.update({
					data: data,
					autoRow: true
				});
				affinityAppName.append(selectedAffinityAppName)
			}
		});
		
		return affinityAppName;
	}
</script>